import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { api } from '@/utils/request'

export interface UserInfo {
  id: number
  idNumber: string
  name: string
  birthDateFirst6: string
  withdrawalBank: string
  withdrawalAccount: string
  accountHolder: string
  mobileCarrier: string
  mobileNumber: string
  entryCode: string
  status: string
  createdAt: string
  updatedAt: string
}

export interface UserBalance {
  id: number
  userId: number
  balance: number
  frozen: number
  total: number
  createdAt: string
  updatedAt: string
}

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref<string | null>(null)
  const userInfo = ref<UserInfo | null>(null)
  const userBalance = ref<UserBalance | null>(null)
  const isLoading = ref(false)

  // 计算属性
  const isLoggedIn = computed(() => !!token.value && !!userInfo.value)

  // 初始化认证状态
  const initializeAuth = async () => {
    const storedToken = localStorage.getItem('user_token')
    if (storedToken) {
      token.value = storedToken
      try {
        await fetchUserProfile()
        await fetchUserBalance()
      } catch (error) {
        console.error('사용자 정보 초기화 실패:', error)
        // 如果token无效，清除本地存储
        logout()
      }
    }
  }

  // 登录
  const login = async (idNumber: string, password: string): Promise<boolean> => {
    try {
      isLoading.value = true
      
      const response = await api.post('/api/auth/login', {
        idNumber,
        password
      })

      if (response.success) {
        token.value = response.data.token
        userInfo.value = response.data.user
        localStorage.setItem('user_token', response.data.token)
        
        // 获取用户余额
        await fetchUserBalance()
        return true
      }
      
      return false
    } catch (error) {
      console.error('Login failed:', error)
      return false
    } finally {
      isLoading.value = false
    }
  }

  // 获取用户资料
  const fetchUserProfile = async () => {
    try {
      const response = await api.get('/api/auth/profile')
      if (response.success) {
        userInfo.value = response.data
      }
    } catch (error) {
      console.error('사용자 프로필 조회 실패:', error)
      throw error
    }
  }

  // 获取用户余额
  const fetchUserBalance = async () => {
    try {
      const response = await api.get('/api/balance')
      if (response.success) {
        userBalance.value = response.data
      }
    } catch (error) {
      console.error('사용자 잔액 조회 실패:', error)
      // 余额获取失败不应该影响登录状态
    }
  }

  // 刷新余额（在充值、提现后调用）
  const refreshBalance = async () => {
    await fetchUserBalance()
  }

  // 登出
  const logout = () => {
    token.value = null
    userInfo.value = null
    userBalance.value = null
    localStorage.removeItem('user_token')
  }

  // 更新用户信息
  const updateUserInfo = (info: Partial<UserInfo>) => {
    if (userInfo.value) {
      userInfo.value = { ...userInfo.value, ...info }
    }
  }

  // 格式化余额显示
  const formatBalance = (amount: number): string => {
    return amount.toLocaleString('ko-KR')
  }

  // 获取可用余额
  const getAvailableBalance = (): number => {
    return userBalance.value?.balance || 0
  }

  // 获取冻结余额
  const getFrozenBalance = (): number => {
    return userBalance.value?.frozen || 0
  }

  // 获取总余额
  const getTotalBalance = (): number => {
    return userBalance.value?.total || 0
  }

  return {
    // 状态
    token,
    userInfo,
    userBalance,
    isLoading,
    
    // 计算属性
    isLoggedIn,
    
    // 方法
    initializeAuth,
    login,
    fetchUserProfile,
    fetchUserBalance,
    refreshBalance,
    logout,
    updateUserInfo,
    formatBalance,
    getAvailableBalance,
    getFrozenBalance,
    getTotalBalance
  }
})
